<?php
/**
 * 工单交款期数详情
 * User: Administrator
 * Date: 2018/7/26/026
 * Time: 21:13
 */

namespace app\lib\Order\OrderInfo;


use app\model\OrderMoneyModel;
use app\model\OrderMoneyRecordModel;

class GetOrderMoney
{
    protected $orderId;
    protected $periods;
    protected $model;
    protected $table;
    protected $cache;
    protected $cacheName;
    protected $moneyId;
    public function __construct($orderId,$cache=true)
    {
        $this->cacheName = Md5('OrderMoneyInfo_'.$this->orderId.'_cache');
        $this->orderId = $orderId;
    }

    public function setMoneyId($moneyId){
        $this->moneyId = $moneyId;
        return $this;
    }
    /**
     * 获取交款分期表
     * @return OrderMoneyModel
     */
    protected function getOrderMoneyModel(){
        if(empty($this->model)){
            $this->model = (new OrderMoneyModel());
        }
        return $this->model;
    }

    /**
     * 获取交款分期记录
     * @return OrderMoneyRecordModel
     */
    protected function getOrderMoneyRecordModel(){
        if(empty($this->table)){
            $this->table = (new  OrderMoneyRecordModel());
        }
        return $this->table;
    }
    /**
     * 第一期交款情况
     * @return bool
     */
    public function isFirstMoney(){
        /*开启缓存*/
        if($this->cache){
            /*获取缓存*/
            $cache = $this->getCache();
            /*获取结果*/
            $moneyModelId = $cache[0]['status'];
        }
        /*未开启缓存*/
        if(!$this->cache){
            /*获取数据库实例化*/
            $model =  $this->getOrderMoneyModel();
            /*获取该工单第一条交款数据*/
            $id = $model->where($model->_orderId,$this->orderId)->order($model->_id.' asc ')->value($model->_id);
            /*实例化交款记录*/
            $moneyModel = $this->getOrderMoneyRecordModel();
            /*获取该条记录是否存在并交款*/
            $map = [$moneyModel->_orderMoneyId=>$id,$moneyModel->_status=>1];
            $moneyModelId =  $moneyModel->where($map)->value($moneyModel->_id);
        }
        return empty($moneyModelId)?false:true;
    }

    /**
     * 获取全部
     * 返回结果集
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllData(){
        /*查询缓存*/
        if($this->cache){
            /*获取缓存*/
            $data = $this->getCache();
        }
        /*查询数据库*/
        if(!$this->cache){
            $model =  $this->getOrderMoneyModel();
            $moneyModel = $this->getOrderMoneyRecordModel();
            $join = [
                ['OrderMoneyRecord b','a.'.$model->_id.'= b.'.$moneyModel->_orderMoneyId,'left'],
            ];
            $field =[
                'a.'.$model->_id,'a.'.$model->_name,
                'a.'.$model->_money, 'b.'.$moneyModel->_status
            ];
            $map = [$model->_orderId=>$this->orderId];
            $data = $model->alias('a')->where($map)->join($join)
                ->order('a.'.$model->_id.' asc')->field($field)->select();
        }
        /*
         * 返回结果集
         * $data = [
         *      0=>[
         *        'id'=>'xxxx','name'=>'xxxx','money'=>'xxxx','status'=>'1'
         *      ],
         *      1=>[
         *        'id'=>'xxxx','name'=>'xxxx','money'=>'xxxx','status'=>'0'
         *      ],
         *      2=>[
         *        'id'=>'xxxx','name'=>'xxxx','money'=>'xxxx','status'=>'0'
         *      ],
         * ]
         * */
        return $data;
    }

    /**
     * 获取缓存
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getCache(){
        $cacheData = cache($this->cacheName);

        if($cacheData){
            $cacheData = json_decode($cacheData,true);
        }

        if(!($cacheData)){
            $cacheData =    $this->generateCache();
        }

        return $cacheData;
    }

    /**
     * 生成缓存
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function generateCache(){
        $this->cache = false;
        $data =  $this->getAllData();
        cache($this->cacheName,json_encode($data),604800);
        return $data;
    }

    /**
     * 清空缓存
     * @return bool
     */
    public function delCache(){
        cache($this->cacheName,null);
        return true;
    }

    /**
     * 获取最近一期未交款的信息
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * ($data = ['id'=>xx,'name'=>xxx,money=>xxx,status=>'xxxx'])
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNoPayRecord(){
        $result = [];
        if($this->cache){
            $data =  $this->getCache();
            foreach ($data as $v){
                if(empty($v['status'])){
                    $result  = $v;
                    break;
                }
            }
        }else{
            $model =  $this->getOrderMoneyModel();
            $moneyModel = $this->getOrderMoneyRecordModel();
            $join = [
                ['OrderMoneyRecord b','a.'.$model->_id.'= b.'.$moneyModel->_orderMoneyId,'left'],
            ];
            $field =[
                'a.'.$model->_id,'a.'.$model->_name,
                'a.'.$model->_money, 'b.'.$moneyModel->_status
            ];
            $map = ['a.'.$model->_orderId=>$this->orderId,'b.'.$moneyModel->_status =>['neq',1]];
            $result = $model->alias('a')->where($map)->join($join)
                ->order('a.'.$model->_id.' asc')->field($field)->find();
        }
        return $result;
    }

    /**
     * 获取指定的某期交款详情
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFindInfo(){
        $result = [];
        if(empty($this->moneyId) || !is_numeric($this->moneyId) || $this->moneyId<0){
            exception('交款日期参数错误');
        }
        if($this->cache){
            $data =  $this->getCache();
            foreach ($data as $v){
                if($v['id'] =$this->moneyId){
                    $result  = $v;
                    break;
                }
            }
        }else{
            $model =  $this->getOrderMoneyModel();
            $moneyModel = $this->getOrderMoneyRecordModel();
            $join = [
                ['OrderMoneyRecord b','a.'.$model->_id.'= b.'.$moneyModel->_orderMoneyId,'left'],
            ];
            $field =[
                'a.'.$model->_id,'a.'.$model->_name,
                'a.'.$model->_money, 'b.'.$moneyModel->_status,'b.'.$moneyModel->_id.' as moneyId'
            ];
            $map = ['a.'.$model->_orderId=>$this->orderId,'a.'.$model->_id =>$this->moneyId];
            $result = $model->alias('a')->where($map)->join($join)
                ->order('a.'.$model->_id.' asc')->field($field)->find();
        }
        return $result;
    }

    /**
     * 是否全部交款完毕
     * @return bool
     */
    public function isAllPayMoney(){
        /*获取全部没交款信息*/
        $model =  $this->getOrderMoneyModel();
        $moneyModel = $this->getOrderMoneyRecordModel();
        $join = [
            ['OrderMoneyRecord b','a.'.$model->_id.'= b.'.$moneyModel->_orderMoneyId,'left'],
        ];
        $map = ['a.'.$model->_orderId=>$this->orderId,'b.'.$model->_status=>['neq',1]];
        $result = $model->alias('a')->where($map)->join($join)->value('a.'.$model->_id);
        /*如果为空就是全部交款，没有就是存在待交款*/
        return empty($result)?true:false;
    }
}